/**
 * 数据统计页面JavaScript逻辑
 */

let statusChart = null;
let vaccineTypeChart = null;
let inventoryChart = null;

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 检查登录状态
    if (!Auth.isLoggedIn()) {
        window.location.href = '../login.html';
        return;
    }

    // 检查用户角色
    if (!Auth.checkRole(UserRole.SITE_ADMIN)) {
        UI.showMessage('您没有权限访问此页面', 'danger');
        setTimeout(() => {
            Auth.logout();
        }, 2000);
        return;
    }

    // 初始化页面
    init();
});

/**
 * 初始化页面
 */
async function init() {
    // 显示用户信息
    displayUserInfo();
    
    // 检查并显示低库存预警
    await checkAndShowLowStockAlert();
    
    // 初始化图表
    initCharts();
    
    // 加载统计数据
    await loadStatistics();
}

/**
 * 显示用户信息
 */
function displayUserInfo() {
    const userInfo = Auth.getUserInfo();
    if (userInfo) {
        const userName = userInfo.account || '管理员';
        document.getElementById('userName').textContent = userName;
        
        // 设置头像首字母
        const avatar = document.getElementById('userAvatar');
        avatar.textContent = userName.charAt(0).toUpperCase();
    }
}

function normalizeAppointmentPage(data) {
    if (!data) {
        return [];
    }
    if (Array.isArray(data)) {
        return data;
    }
    if (Array.isArray(data.records)) {
        return data.records;
    }
    return [];
}

/**
 * 初始化图表
 */
function initCharts() {
    // 预约状态分布饼图
    statusChart = echarts.init(document.getElementById('statusChart'));
    
    // 疫苗类型分布饼图
    vaccineTypeChart = echarts.init(document.getElementById('vaccineTypeChart'));
    
    // 库存柱状图
    inventoryChart = echarts.init(document.getElementById('inventoryChart'));
    
    // 响应式调整
    window.addEventListener('resize', function() {
        statusChart.resize();
        vaccineTypeChart.resize();
        inventoryChart.resize();
    });
}

/**
 * 加载统计数据
 */
async function loadStatistics() {
    try {
        // 获取用户信息中的接种点ID
        const userInfo = Auth.getUserInfo();
        
        // 加载预约数据：获取所有预约记录（不限制日期范围）
        let allAppointments = [];
        try {
            // 方法1：尝试通过日历接口获取所有有预约的日期，然后获取详情
            const currentDate = new Date();
            const monthPromises = [];
            
            // 获取最近12个月的日历数据（扩大范围）
            for (let i = 0; i < 12; i++) {
                const date = new Date(currentDate.getFullYear(), currentDate.getMonth() - i, 1);
                const monthStr = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
                monthPromises.push(
                    HttpClient.get(`/admin/appointment/calendar?month=${monthStr}`)
                        .then(calendarData => {
                            if (!calendarData || !Array.isArray(calendarData)) {
                                return [];
                            }
                            // 获取所有有预约的日期
                            const datesWithAppointments = calendarData
                                .filter(day => day.hasAppointments && day.date)
                                .map(day => day.date);
                            
                            // 批量获取这些日期的预约详情
                            const dayPromises = datesWithAppointments.map(dateStr => 
                                HttpClient.get(`/admin/appointment/by-date?date=${dateStr}`)
                                    .then(appointments => {
                                        // 确保返回的是数组
                                        if (Array.isArray(appointments)) {
                                            return appointments;
                                        }
                                        return [];
                                    })
                                    .catch(err => {
                                        console.warn(`获取日期 ${dateStr} 的预约失败:`, err);
                                        return [];
                                    })
                            );
                            
                            return Promise.all(dayPromises);
                        })
                        .catch(err => {
                            console.warn(`获取月份 ${monthStr} 的日历数据失败:`, err);
                            return [];
                        })
                );
            }
            
            const monthResults = await Promise.all(monthPromises);
            monthResults.forEach(monthData => {
                if (Array.isArray(monthData)) {
                    monthData.forEach(dayAppointments => {
                        if (Array.isArray(dayAppointments)) {
                            allAppointments = allAppointments.concat(dayAppointments);
                        }
                    });
                }
            });
            
            console.log('通过日历接口获取到的预约数量:', allAppointments.length);
            
            // 如果还是没有数据，尝试获取今日预约
            if (allAppointments.length === 0) {
                console.warn('通过日历接口未获取到数据，尝试获取今日预约');
                try {
                    const appointmentPage = await HttpClient.get('/admin/appointment/today?pageNum=1&pageSize=1000');
                    allAppointments = normalizeAppointmentPage(appointmentPage);
                    console.log('通过今日预约接口获取到的预约数量:', allAppointments.length);
                } catch (e) {
                    console.warn('获取今日预约失败:', e);
                }
            }
        } catch (error) {
            console.error('加载预约数据失败:', error);
            // 如果所有方法都失败，至少尝试获取今日预约
            try {
                const appointmentPage = await HttpClient.get('/admin/appointment/today?pageNum=1&pageSize=1000');
                allAppointments = normalizeAppointmentPage(appointmentPage);
                console.log('异常处理中获取到的预约数量:', allAppointments.length);
            } catch (e) {
                console.error('获取今日预约也失败:', e);
                allAppointments = [];
            }
        }
        
        console.log('加载到的预约数据数量:', allAppointments.length);
        if (allAppointments.length > 0) {
            console.log('第一条预约数据示例:', allAppointments[0]);
        }
        
        // 更新统计卡片
        updateStatisticsCards(allAppointments);
        
        // 更新预约状态分布图
        updateStatusChart(allAppointments);
        
        // 更新疫苗类型分布图
        updateVaccineTypeChart(allAppointments);
        
        // 加载库存数据
        const inventories = await HttpClient.get('/admin/inventory/list');
        
        // 更新库存图表
        updateInventoryChart(inventories);
        
    } catch (error) {
        console.error('加载统计数据失败:', error);
        UI.showMessage('加载统计数据失败', 'danger');
    }
}

/**
 * 更新统计卡片
 */
function updateStatisticsCards(appointments) {
    if (!appointments || !Array.isArray(appointments)) {
        return;
    }
    
    // 总预约数
    document.getElementById('totalAppointments').textContent = appointments.length;
    
    // 待接种（状态码：1=待接种）
    const pending = appointments.filter(a => a.appointmentStatus === 1).length;
    document.getElementById('pendingAppointments').textContent = pending;
    
    // 已完成（状态码：2=已接种）
    const completed = appointments.filter(a => a.appointmentStatus === 2).length;
    document.getElementById('completedAppointments').textContent = completed;
}

/**
 * 更新预约状态分布图
 */
function updateStatusChart(appointments) {
    if (!appointments || !Array.isArray(appointments)) {
        statusChart.setOption({
            title: {
                text: '暂无数据',
                left: 'center',
                top: 'center',
                textStyle: {
                    color: '#999',
                    fontSize: 14
                }
            },
            series: []
        });
        return;
    }
    
    // 统计各状态数量（状态码：1=待接种, 2=已完成, -1=已取消, 0=已逾期）
    // 注意：已取消的预约已被后端过滤，这里不会统计到
    let pending = 0;
    let completed = 0;
    let cancelled = 0;
    
    appointments.forEach(a => {
        const status = a.appointmentStatus !== undefined ? a.appointmentStatus : 
                      (a.appointment_status !== undefined ? a.appointment_status : 
                      (a.status !== undefined ? a.status : null));
        
        if (status === 1) {
            pending++;
        } else if (status === 2) {
            completed++;
        } else if (status === -1) {
            cancelled++;
        }
    });
    
    console.log('预约状态统计 - 待接种:', pending, '已完成:', completed, '已取消:', cancelled);
    console.log('总预约数:', appointments.length);
    console.log('预约数据示例:', appointments.length > 0 ? appointments[0] : '无数据');
    
    // 如果没有任何数据，显示提示
    const total = pending + completed + cancelled;
    if (total === 0) {
        statusChart.setOption({
            title: {
                text: '暂无预约数据',
                left: 'center',
                top: 'center',
                textStyle: {
                    color: '#999',
                    fontSize: 14
                }
            },
            series: []
        });
        return;
    }
    
    const option = {
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
            orient: 'vertical',
            left: 'left',
            top: 'middle'
        },
        series: [
            {
                name: '预约状态',
                type: 'pie',
                radius: ['40%', '70%'],
                center: ['60%', '50%'],
                avoidLabelOverlap: false,
                label: {
                    show: true,
                    position: 'outside',
                    formatter: '{b}: {c}'
                },
                labelLine: {
                    show: true
                },
                data: [
                    { value: pending, name: '待接种', itemStyle: { color: '#faad14' } },
                    { value: completed, name: '已完成', itemStyle: { color: '#52c41a' } },
                    { value: cancelled, name: '已取消', itemStyle: { color: '#f5222d' } }
                ],
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }
        ]
    };
    
    statusChart.setOption(option);
}

/**
 * 更新疫苗类型分布图
 */
function updateVaccineTypeChart(appointments) {
    if (!appointments || !Array.isArray(appointments)) {
        // 显示空数据提示
        vaccineTypeChart.setOption({
            title: {
                text: '暂无数据',
                left: 'center',
                top: 'center',
                textStyle: {
                    color: '#999',
                    fontSize: 14
                }
            },
            series: []
        });
        return;
    }
    
    // 统计各疫苗类型数量
    const typeCount = {};
    appointments.forEach(a => {
        // 尝试多种可能的字段名
        let type = a.vaccineType || a.vaccine_type || a.type;
        
        // 如果type是数字，转换为字符串
        if (type !== undefined && type !== null) {
            type = String(type);
            if (type !== '' && type !== 'null' && type !== 'undefined') {
                typeCount[type] = (typeCount[type] || 0) + 1;
            }
        }
    });
    
    console.log('疫苗类型统计:', typeCount);
    console.log('预约数据中的疫苗类型字段示例:', appointments.length > 0 ? {
        vaccineType: appointments[0].vaccineType,
        vaccine_type: appointments[0].vaccine_type,
        type: appointments[0].type
    } : '无数据');
    
    const colors = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4'];
    const data = Object.keys(typeCount).map((type, index) => {
        // 尝试解析类型码
        let typeCode = parseInt(type);
        if (isNaN(typeCode)) {
            typeCode = type; // 如果无法解析，直接使用原值
        }
        return {
            value: typeCount[type],
            name: Format.vaccineType ? Format.vaccineType(typeCode) : `类型${typeCode}`,
            itemStyle: { color: colors[index % colors.length] }
        };
    });
    
    // 如果没有数据，显示提示
    if (data.length === 0) {
        vaccineTypeChart.setOption({
            title: {
                text: '暂无数据',
                left: 'center',
                top: 'center',
                textStyle: {
                    color: '#999',
                    fontSize: 14
                }
            },
            series: []
        });
        return;
    }
    
    const option = {
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
            orient: 'vertical',
            left: 'left',
            top: 'middle'
        },
        series: [
            {
                name: '疫苗类型',
                type: 'pie',
                radius: ['40%', '70%'],
                center: ['60%', '50%'],
                avoidLabelOverlap: false,
                label: {
                    show: true,
                    position: 'outside',
                    formatter: '{b}: {c}'
                },
                labelLine: {
                    show: true
                },
                data: data,
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }
        ]
    };
    
    vaccineTypeChart.setOption(option);
}

/**
 * 更新库存图表
 */
function updateInventoryChart(inventories) {
    if (!inventories || !Array.isArray(inventories)) {
        return;
    }
    
    // 更新库存种类数量
    document.getElementById('inventoryCount').textContent = inventories.length;
    
    // 准备图表数据
    const vaccineNames = inventories.map(i => i.vaccineName || '未知');
    const quantities = inventories.map(i => i.quantity || 0);
    const thresholds = inventories.map(i => i.lowStockThreshold || 100);
    
    const option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        legend: {
            data: ['当前库存', '预警阈值']
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: vaccineNames,
            axisLabel: {
                interval: 0,
                rotate: 30
            }
        },
        yAxis: {
            type: 'value',
            name: '数量'
        },
        series: [
            {
                name: '当前库存',
                type: 'bar',
                data: quantities,
                itemStyle: {
                    color: '#4A90E2'
                },
                markLine: {
                    silent: true,
                    lineStyle: {
                        color: '#f5222d',
                        type: 'dashed'
                    },
                    data: []
                }
            },
            {
                name: '预警阈值',
                type: 'line',
                data: thresholds,
                itemStyle: {
                    color: '#faad14'
                },
                lineStyle: {
                    type: 'dashed'
                }
            }
        ]
    };
    
    inventoryChart.setOption(option);
}

/**
 * 退出登录
 */
function handleLogout() {
    UI.confirm('确定要退出登录吗？', () => {
        Auth.logout();
    });
}

